package 算法思维系列;

import java.util.Stack;

public class 基本计算器II_227 {


    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        //记录num前的符号
        char sign = '+';

        int num = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                num = 10 * num + (c - '0');
            }
//            遇到左括号要递归计算num
            if (c == '(') {
                num = calculate(s);
            }


            if ((!Character.isDigit(c) && c != ' ') || i == s.length() - 1) {
                switch (sign) {
                    case '+':
                        stack.push(num);
                        break;
                    case '-':
                        stack.push(-num);
                        break;
                    case '*':
                        Integer pop = stack.pop();
                        stack.push(pop * num);
                        break;
                    case '/':
                        Integer pop2 = stack.pop();
                        stack.push(pop2 / num);
                        break;
                }

                sign = c;
                num = 0;
//                遇到右括号结束递归，返回结果
                if (c == ')') {
                    break;
                }
            }
        }
        //将栈中所有元素求和就是答案
        int res = 0;
        while (!stack.isEmpty()) {
            res += stack.peek();
            stack.pop();
        }
        return res;
    }
}
